﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;

public partial class DynamicReport : ExtBaseRpt
{
    protected void Page_Load(object sender, EventArgs e)
    {
        mid = Request.Params["mid"];
        if (!X.IsAjaxRequest)
        {
            //加载表头 查找网格
            //this.GridPanel1.ColumnModel.Add(BuildColumns(mid, Session["UserID"].ToString(), "GridPanel1", null));
            //BtnFind("","");
            //加载条件控件
            BuildCtrls("param",this.ColumPanel);
            //加载输出项
            ShowFiledWindows();
            //加载报表网格

        }
    }

    #region 创建条件控件
    private void BuildCtrls(string name,FormPanel pn)
    {
        string sql = @"select mu_id,lindx,fieldname,fielddisplay,mu_visible,fieldwidth,datatype,gridfoot,showtype,fieldreadonly,isctrl,
                    datatype,showtype,ctrltype,ctrl_x,ctrl_y,iskeyid,ismust
                    from sys_moduleslayout a 
                    inner join sys_modulesuserlayout b on b.fid =lid 
                    inner join sys_modules m on m.mid = a.mid 
                    where m.parentid = " + mid + " and m.modulecode='" + name + "'"
                 + " and userid=" + Session["UserID"] + " order by lindx";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds != null)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (dr["isctrl"].ToString().ToLower() == "true")
                {
                    //文本型
                    if (dr["ctrltype"].ToString() == "0")
                    {
                        TextField text = new TextField();
                        text.ID = "txt" + dr["fieldname"].ToString();
                        text.Name = dr["fielddisplay"].ToString();
                        text.FieldLabel = dr["fielddisplay"].ToString();
                        text.Padding = 3;
                        text.LabelWidth = 80;
                        if (dr["ismust"].ToString() == "True")
                            text.AllowBlank = false;
                        //text.Width = Convert.ToInt32(dr["fieldwidth"]);
                        pn.Items.Add(text);
                    }
                    // 日期型
                    else if (dr["ctrltype"].ToString() == "1")
                    {
                        DateField text = new DateField();
                        text.ID = "txt" + dr["fieldname"].ToString();
                        text.Name = dr["fielddisplay"].ToString();
                        text.FieldLabel = dr["fielddisplay"].ToString();
                        //text.Width = Convert.ToInt32(dr["fieldwidth"]);
                        text.Padding = 3;
                        text.LabelWidth = 80;
                        if (dr["ismust"].ToString() == "True")
                            text.AllowBlank = false;
                        //text.Format="yyyy-MM-dd";
                        pn.Items.Add(text);
                    }
                    // 备注
                    else if (dr["ctrltype"].ToString() == "2")
                    {
                        TextArea text = new TextArea();
                        text.ID = "txt" + dr["fieldname"].ToString();
                        text.Name = dr["fielddisplay"].ToString();
                        text.FieldLabel = dr["fielddisplay"].ToString();
                        //text.Width = Convert.ToInt32(dr["fieldwidth"]);
                        text.Padding = 3;
                        text.LabelWidth = 80;
                        //text.Format="yyyy-MM-dd";
                        if (dr["ismust"].ToString() == "True")
                            text.AllowBlank = false;
                        pn.Items.Add(text);
                    }
                    // 选择框
                    else if (dr["ctrltype"].ToString() == "4")
                    {
                        Checkbox text = new Checkbox();
                        text.ID = "txt" + dr["fieldname"].ToString();
                        text.Name = dr["fielddisplay"].ToString();
                        text.BoxLabel = dr["fielddisplay"].ToString();
                        //text.Width = Convert.ToInt32(dr["fieldwidth"]);
                        text.Padding = 3;
                        text.LabelWidth = 80;
                        //text.Format="yyyy-MM-dd";
                        pn.Items.Add(text);
                    }
                }
            }
        }
    }
    #endregion

    protected void RefreshDataSet(object sender, StoreReadDataEventArgs e)
    {
        BtnFind("","");
    }
    protected void Store1_Submit(object sender, StoreSubmitDataEventArgs e)
    {
        //导出EXCEL
        ExtGridToExcel(mid, "xls", e.Xml, this.Response, this.Title);
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void BtnFind(string fields,string vals)
    {
        //if (HD_Fiels.Value.ToString() == "")
        //{
        //    ShowBox("请选择输出项目！");
        //    return;
        //}
        string dynaSumFilds = "";
        string dynaFilds = "";

        if (this.HD_Fiels.Value.ToString() != "")
        {
            string[] fld = HD_Fiels.Value.ToString().Split(',');
            foreach (string s in fld)
            {
                if (s.ToLower().IndexOf("amount") > 0 || s.IndexOf("qty") > 0)
                {
                    dynaSumFilds += "sum(" + s + "),";
                }
                else
                {
                    dynaFilds += s + ",";
                }

            }
        }
        string sql = "";
        dynaSumFilds = dynaSumFilds.TrimEnd(',');
        string[] param = vals.Split(',');
        foreach (string p in param)
        {
            sql += "'"+p+"',";
        }
        sql += " '" + dynaFilds + dynaSumFilds + "','" + dynaFilds.TrimEnd(',') +"'";
        //ShowBox("KM_SalePosAnalysis " + sql);
        //StoreColumns(Store1, mid, "GridPanel1");
        DataSet ds = db.DM_GetDateSet("KM_SalePosAnalysis "+sql);
        DynaGridResult(ds);
    }
    #region 动态加载报表显示结果
    private void DynaGridResult(DataSet ds)
    {
        if (ds == null) return;

        Store store = this.Store1;
        GridPanel grid = this.GridPanel1;

        // Clear Collections to remove old Data and Models
        store.Reader.Clear();
        //grid.SelectionModel.Clear();
        grid.ColumnModel.Columns.Clear();
        store.Model.Clear();
        //store.Model.Add(new Model
        //{
        //    Fields = 
        //    {
        //        new ModelField("ShopName"),
        //        new ModelField("CashAmt", ModelFieldType.Float),
        //    }
        //});
        

        //grid.SelectionModel.Add(new RowSelectionModel { Mode = SelectionMode.Single });
        //grid.ColumnModel.Columns.Add(new ColumnBase[] { 
        //    new Column 
        //    {
        //        Text = "ShopName",
        //        DataIndex = "ShopName",
        //        Flex = 1
        //    },
        //    new Column
        //    {
        //        Text = "CashAmt",
        //        DataIndex = "CashAmt",
        //        Renderer = { Format = RendererFormat.UsMoney }
        //    }
        //});
        Model md = new Model();
        List<ColumnBase> list = new List<ColumnBase>();

        DataTable dt = ds.Tables[0];
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            //根据结果集创建Store
            ModelField field = new ModelField();
            field.Name = dt.Columns[i].ToString();
            md.Fields.Add(field);
            //创建grid colums
            Column cl = new Column();
            cl.Text = dt.Columns[i].ToString();
            cl.DataIndex = dt.Columns[i].ToString();
            list.Add(cl);
        }
        store.Model.Add(md);
        store.DataSource = ds;
        store.DataBind();
        grid.ColumnModel.Columns.Add(list);
        grid.Render();
    }
    #endregion
    #region 输出项项目加载
    protected void ShowFiledWindows()
    {
        //加载报表输出项
        string sql = @"select mu_id,lindx,fieldname,fielddisplay,mu_visible,fieldwidth,datatype,gridfoot,showtype,fieldreadonly,isctrl,
                    datatype,showtype,ctrltype,ctrl_x,ctrl_y,iskeyid,ismust
                    from sys_moduleslayout a 
                    inner join sys_modulesuserlayout b on b.fid =lid 
                    inner join sys_modules m on m.mid = a.mid 
                    where m.parentid = " + mid + " and m.modulecode='GridPanel1'"
                 + " and userid=" + Session["UserID"] + " order by lindx";
        DataSet ds = mydb.DM_GetDateSet(sql);

        //Node reprotNode = new Node();
        //reprotNode.Text = "报表输出项";
        //reprotNode.Icon = Ext.Net.Icon.Folder;
        foreach(DataRow dr in ds.Tables[0].Rows)
        {
            Node childNode = new Node();
            childNode.NodeID = dr["fieldname"].ToString();
            childNode.Text = dr["fielddisplay"].ToString();
            childNode.Leaf = true;
            childNode.Checked = false;
            TreePanel1.Root[0].Children[0].Children.Add(childNode);
        }
        //this.TreePanel1.Root.Add(reprotNode);
        //加载基础资料
        //this.Window1.Show();
        sql = "select * from sys_modules where parentid = " + mid+" and moduletype = 4";
        ds = mydb.DM_GetDateSet(sql);
        DataSet ds2;
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            Node mNode = new Node();
            mNode.NodeID = dr["mid"].ToString();
            mNode.Text = dr["modulename"].ToString();
            

            sql = @"select mu_id,lindx,fieldname,fielddisplay,mu_visible,fieldwidth,datatype,gridfoot,showtype,fieldreadonly,isctrl,
                    datatype,showtype,ctrltype,ctrl_x,ctrl_y,iskeyid,ismust
                    from sys_moduleslayout a 
                    inner join sys_modulesuserlayout b on b.fid =lid 
                    inner join sys_modules m on m.mid = a.mid 
                    where m.parentid = " + mid + " and m.modulecode='" + dr["modulecode"].ToString() + "'"
                 + " and userid=" + Session["UserID"] + " order by lindx";

            ds2 = mydb.DM_GetDateSet(sql);
            //Node reprotNode = new Node();
            //reprotNode.Text = "报表输出项";
            //reprotNode.Icon = Ext.Net.Icon.Folder;
            foreach (DataRow dr2 in ds2.Tables[0].Rows)
            {
                Node childNode = new Node();
                childNode.NodeID = dr2["fieldname"].ToString();
                childNode.Text = dr2["fielddisplay"].ToString();
                childNode.Leaf = true;
                childNode.Checked = false;
                mNode.Children.Add(childNode);
            }
            TreePanel1.Root[0].Children.Add(mNode);
        }
    }
    #endregion

}